<template>
  <el-container class="official-account-management_official-account-user">
    <el-main>
      <el-button class="fixedRight" type="primary" icon="el-icon-sort" size="small" @click="$showHide()" />
      <el-card shadow="never" class="selectCard searchColumn">
        <el-form label-position="right" label-width="7.5rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="昵称：">
                <el-input v-model="params.nickName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否关注：">
                <el-select v-model="params.subscribe">
                  <el-option :value="''" label="全部" />
                  <el-option :value="1" label="已关注" />
                  <el-option :value="0" label="未关注" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别：">
                <el-select v-model="params.sex">
                  <el-option :value="''" label="全部" />
                  <el-option :value="1" label="男" />
                  <el-option :value="2" label="女" />
                  <el-option :value="0" label="未知" />
                </el-select>
              </el-form-item>
            </el-col>
            <div class="searchColumn">
              <el-col :span="16">
                <el-form-item label="关注时间：">
                  <el-date-picker
                    v-model="params.orderDate"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="渠道来源：">
                  <el-select v-model="params.subscribeScene">
                    <el-option :value="''" label="全部" />
                    <el-option v-for="item in subscribeSceneList" :key="item.value" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="取消关注时间：">
                  <el-date-picker
                    v-model="params.orderDate1"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  />
                  <!-- <el-date-picker v-model="params.cancelSubscribeStartTime" type="datetime" />
                  <i>至</i>
                  <el-date-picker v-model="params.cancelSubscribeEndTime" type="datetime" /> -->
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="标签：">
                  <el-select v-model="params.tagsId" filterable>
                    <el-option :value="''" label="全部" />
                    <el-option v-for="item in tagTypeList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </div>
            <!-- filterable  -->
          </el-row>
          <SearchButton :default-params="params" @refreshParams="refreshParams" @getList="getList1" />
        </el-form>
      </el-card>
      <el-card shadow="never" class="tableCard">
        <vxe-toolbar :custom="{icon: 'el-icon-s-operation'}" :refresh="{query: getList1}">
          <template v-slot:buttons>
            <!-- <el-button icon="el-icon-download">导出</el-button> -->
            <el-dropdown style="margin: 0 0 0 10px" placement="bottom-start" @command="getTag">
              <el-button type="primary" size="small">
                打标签<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :disabled="checkList.length === 0" command="1">对选中的人加标签</el-dropdown-item>
                <el-dropdown-item command="2">对筛选出来的{{ total }}人加标签</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown style="margin: 0 10px" placement="bottom-start" @command="removeTag">
              <el-button type="primary" size="small">
                去除标签<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :disabled="checkList.length === 0" command="1">对选中的人去除标签</el-dropdown-item>
                <el-dropdown-item command="2">对筛选出来的{{ total }}人去除标签</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="primary" icon="el-icon-refresh" size="small" @click="syncFansFromWechat">同步粉丝数据</el-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="listTree"
          border
          resizable
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="list"
          width
          max-height="500"
          :print-config="{}"
          row-id="id"
          highlight-current-row
          text-algin="center"
          :checkbox-config="{checkRowKeys: checkList, checkStrictly: false}"
          @checkbox-all="selectAll"
          @checkbox-change="selectChangeEvent"
        >
          <vxe-table-column type="checkbox" width="35" />
          <vxe-table-column width="70" title="头像">
            <template slot-scope="scope">
              <img width="50" height="50" :src="scope.row.headImgurl" alt="">
            </template>
          </vxe-table-column>
          <vxe-table-column width="250" field="nickName" title="昵称" />
          <vxe-table-column width="50" field="sexName" title="性别" />
          <vxe-table-column width="120" field="subscribeSceneName" title="关注渠道" />
          <vxe-table-column width="150" field="subscribeTime" title="关注时间" />
          <vxe-table-column width="300" field="tags" title="标签">
            <template slot-scope="scope">
              <span>{{ scope.row.tags === null ? '无' : scope.row.tags }}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="80" title="关注状态">
            <template slot-scope="scope">
              <span>{{ scope.row.subscribe === 1 ? '已关注' : '未关注' }}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="100" field="qrSceneStr" title="关注次数" align="right">
            <template slot-scope="scope">
              <span>{{ scope.row.qrSceneStr === '' ? 0 : scope.row.qrSceneStr }}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="140" field="qrScene" title="二维码扫描场景" />
          <vxe-table-column width="300" title="所在地区">
            <template slot-scope="scope">
              {{ scope.row.country }} {{ scope.row.province }} {{ scope.row.city }}
            </template>
          </vxe-table-column>
          <vxe-table-column width="250" field="openId" title="openId" />
          <vxe-table-column width="100" field="language" title="语言" />
          <vxe-table-column width="200" field="remark" title="备注" />
          <vxe-table-column width="130" title="操作" fixed="right" align="center" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="seeInfo(scope.row.id, 1)">查看</el-button>
              <el-button type="text" size="mini" @click="seeInfo(scope.row.id, 2)">编辑</el-button>
              <el-button type="text" size="mini" @click="openDialog(scope.row, scope.seq)">消息</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="params.pageNum"
          :page-size.sync="params.pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogFormVisible" width="30%" title="请选择要打的标签" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form>
        <el-row>
          <el-col :span="18">
            <el-form-item label="标签">
              <el-select v-model="tagsIds" multiple filterable placeholder="请选择">
                <el-option v-for="item in tagTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSure">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="infoDialog" :title="title" :close-on-click-modal="false" :visible.sync="infoDialog">
      <el-form :model="paramsDialog" label-position="right" label-width="8rem">
        <el-row>
          <el-col :span="8">
            <el-form-item label="头像：">
              <img width="100" height="100" :src="paramsDialog.headImgurl" alt="">
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="昵称：">
              {{ paramsDialog.nickName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否关注：">
              {{ paramsDialog.subscribe === 1 ? '已关注' : '未关注' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关注渠道：">
              {{ paramsDialog.subscribeSceneName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别：">
              {{ paramsDialog.sexName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="国家：">
              {{ paramsDialog.country }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="省份:">
              {{ paramsDialog.province }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市：">
              {{ paramsDialog.city }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="语言：">
              {{ paramsDialog.language }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="二维码扫描场景：">
              {{ paramsDialog.subscribeSceneName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关注时间：">
              {{ paramsDialog.subscribeTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="取关时间：">
              {{ paramsDialog.cancelSubscribeTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="openId：">
              {{ paramsDialog.openId }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="union_id：">
              {{ paramsDialog.unionId }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签：">
              <div v-if="title === '查看'" class="tag-list">
                <el-tag v-for="tag in paramsDialog.tagsVos" :key="tag.id">{{ tag.name }}</el-tag>
                <el-tag v-if="paramsDialog.tagsVos === null">无</el-tag>
              </div>
              <div v-else class="tag-list">
                <el-tag v-for="tag in paramsDialog.tagsVos" :key="tag.id" closable :disable-transitions="false" @close="handleClose(tag)">{{ tag.name }}</el-tag>
                <el-tag v-for="tag in paramsDialog.autoTagsList" :key="tag.id">{{ tag.name }}</el-tag>
                <el-select v-if="tagVisible" ref="tagAddSelect" v-model="tagValue" filterable class="selectInput" size="small" @change="handleInputConfirm" @blur="handleInputBlur">
                  <el-option v-for="item in addTagList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-button v-else class="button-new-tag el-icon-plus" size="small" @click="showInput" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model="paramsDialog.remark" :disabled="title === '查看'" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoDialog = false">取 消</el-button>
        <el-button v-if="title !== '查看'" type="primary" @click="clickSetSure">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户消息" :close-on-click-modal="false" :visible.sync="userMessageDialog">
      <WxMsg v-if="userMessageDialog" :wx-user-id="wxUserId" />
    </el-dialog>
  </el-container>
</template>

<script>
import SearchButton from '@/components/SearchButton'
import WxMsg from '@/components/wechat-mp/wx-msg/main.vue'
import { searchAllDictionaries } from '@/api/public'
import { checkVaildWxMp, listWxMpFans, syncFansFromWx, viewWxMpFans, modifyWxMpFans, wxMpFansAddTag, wxMpFansDelTag } from '@/api/wxMp'

export default {
  components: {
    WxMsg,
    SearchButton
  },
  data() {
    return {
      tagVisible: false,
      addTagList: [],
      wxUserId: '',
      checkTagList: [],
      title: '',
      subscribeSceneList: [],
      pickerOptions: this.$store.getters.pickerOptions,
      params: {
        orderDate: [],
        orderDate1: [],
        appId: '',
        subscribe: '',
        openId: '',
        unionId: '',
        nickName: '',
        sex: '',
        subscribeStartTime: '',
        subscribeEndTime: '',
        cancelSubscribeStartTime: '',
        cancelSubscribeEndTime: '',
        subscribeScene: '',
        tagsId: '',
        pageNum: 1,
        pageSize: 20
      },
      userMessageDialog: false,
      dialogFormVisible: false,
      infoDialog: false,
      paramsDialog: {},
      tagTypeList: [],
      checkList: [],
      loading: false,
      total: 0,
      fansIds: [],
      tagsIds: [],
      list: []
    }
  },
  created() {
    this.checkCurrentVaildWxMp()
  },
  mount() {
  },
  methods: {
    handleClose(tag) {
      console.log(tag.id)
      this.paramsDialog.tagsVos = this.paramsDialog.tagsVos.filter(item => item.id !== tag.id)
    },
    handleInputConfirm() {
      const data = this.addTagList.find(item => item.id === this.tagValue)
      console.log(data)
      this.paramsDialog.tagsVos.push({
        id: data.id,
        name: data.name
      })
      this.tagVisible = false
    },
    handleInputBlur() {
      setTimeout(() => {
        this.tagVisible = false
      }, 100)
    },
    // tag添加按钮点击事件
    showInput() {
      this.filterAddTagList()
      this.tagVisible = true
      this.tagValue = ''
      this.$nextTick(_ => {
        this.$refs.tagAddSelect.focus()
      })
    },
    filterAddTagList() {
      this.addTagList = JSON.parse(JSON.stringify(this.tagTypeList))
      this.paramsDialog.tagsVos = this.paramsDialog.tagsVos === null ? [] : this.paramsDialog.tagsVos
      this.paramsDialog.tagsVos.forEach(tag => {
        this.addTagList = this.addTagList.filter(item => item.id !== tag.id)
      })
    },

    openDialog(row) {
      this.wxUserId = toString(row.wxUserId)
      this.userMessageDialog = true
    },
    clickSend() {
      console.log(this.$refs.userMessage.tabsParams)
    },
    newSetArr(arr) {
      const obj = {}
      const arr1 = []
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i].id]) {
          arr1.push(arr[i])
          obj[arr[i].id] = true
        }
      }
      return arr1
    },
    clickSetSure() {
      modifyWxMpFans({ id: this.paramsDialog.id, appId: this.paramsDialog.appId, remark: this.paramsDialog.remark,
        tagsList: this.paramsDialog.tagsVos.map(item => item.id) }).then(res => {
        this.$message.success('编辑成功！')
        this.infoDialog = false
        this.getList()
      })
    },
    // 1选中 2全选
    getTag(i) {
      this.tagsIds = []
      this.fansIds = i === '1' ? this.checkList : []
      this.dialogFormVisible = true
    },
    clickSure() {
      if (this.tagsIds.length === 0) {
        this.$message.error('请选择标签')
      } else {
        wxMpFansAddTag({ query: this.params, fansIds: this.fansIds, tagsIds: this.tagsIds }).then(res => {
          this.$message.success('打标签成功！')
          this.dialogFormVisible = false
          this.getList()
        })
      }
    },
    removeTag() {
      const tagsId = this.params.tagsId
      if (tagsId === '') {
        this.$message.error('请在搜索条件中选择要取消的标签！')
      } else {
        const fansIds = this.checkList
        wxMpFansDelTag({ query: this.params, tagsId, fansIds }).then(res => {
          this.$message.success('清除标签成功！')
          this.getList()
        })
      }
    },
    getList1() {
      this.params.pageNum = 1
      this.checkList = []
      this.getList()
      this.getTagTypeList()
    },
    refreshParams(params) {
      this.params = params
      this.getList()
      this.getTagTypeList()
    },
    getTagTypeList() {

    },
    checkCurrentVaildWxMp() {
      checkVaildWxMp().then(res => {
        if (res) {
          if (res === undefined) {
            alert('公众号没有授权，请授权后再操作!')
            this.$router.push(`/wxMp/wxMpAuthorize`)
          } else {
            const objRes = JSON.parse(JSON.stringify(res))
            this.params.appId = objRes.appId
            this.getTagTypeList(this.params.appId)
            this.getSubscribeSceneList()
            this.getList()
          }
        } else {
          alert('公众号没有授权，请授权后再操作!')
          this.$router.push(`/wxMp/wxMpAuthorize`)
        }
      }).catch(() => {
        alert('公众号没有授权，请授权后再操作!')
        this.$router.push(`/wxMp/wxMpAuthorize`)
      })
    },
    getSubscribeSceneList() {
      searchAllDictionaries({ type: 'mp_scene_type' }).then(res => {
        this.subscribeSceneList = res
      })
    },
    getList() {
      if (this.params.orderDate) {
        this.params.subscribeStartTime = this.params.orderDate[0]
        this.params.subscribeEndTime = this.params.orderDate[1]
      }
      if (this.params.orderDate1) {
        this.params.cancelSubscribeStartTime = this.params.orderDate[0]
        this.params.cancelSubscribeEndTime = this.params.orderDate[1]
      }
      listWxMpFans(this.params).then(res => {
        this.list = res.records
        this.total = res.total
        this.checkList.forEach((item, index) => {
          this.list.forEach((it, idx) => {
            if (item === it.id) {
              this.$refs.listTree.setCheckboxRow(this.list[idx], true)
            }
          })
        })
      })
    },
    syncFansFromWechat() {
      this.loading = true
      syncFansFromWx(this.params.appId).then(res => {
        if (res) {
          this.getList()
          this.loading = false
        } else {
          this.loading = false
        }
      })
    },
    seeInfo(id, type) {
      this.title = type === 1 ? '查看' : '编辑'
      viewWxMpFans({ appId: this.params.appId, id }).then(res => {
        this.paramsDialog = res
        this.infoDialog = true
      })
    },
    selectAll(e) {
      if (e.checked) {
        this.checkList.push(...e.records.map(item => item.id))
        this.checkList = Array.from(new Set(this.checkList))
      } else {
        const arr = this.list.map(item => item.id)
        const arr1 = []
        this.checkList.forEach((item, index) => {
          arr.forEach(it => {
            if (item === it) {
              arr1.push(index)
            }
          })
        })
        arr1.reverse().forEach(item => {
          this.checkList.splice(item, 1)
        })
      }
    },
    selectChangeEvent(row) {
      let i = -1
      this.checkList.forEach((item, index) => {
        if (item === row.row.id) {
          i = index
        }
      })
      if (i === -1) {
        this.checkList.push(row.row.id)
      } else {
        this.checkList.splice(i, 1)
      }
    }
  }
}
</script>

<style lang="scss">
.official-account-management_official-account-user{
  .el-dialog__body {
    .el-checkbox-group {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      .el-checkbox {
        width: 20%;
        margin: 0;
      }
    }
  }
  // .tags {
  //   width: 100%;
  //   display: flex;
  //   flex-wrap: wrap;
  //   justify-content: flex-start;
  //   align-items: center;
  //   min-height: 40px;
  //   span {
  //     text-align: center;
  //     width: 19%;
  //     margin-right: 1.25%;
  //     margin-bottom: 10px;
  //     border: 1px solid #409eff;
  //     border-radius: 5px;
  //   }
  //   span:nth-child(5n+5) {
  //     margin-right: 0;
  //   }
  // }
  .tag-list {
    margin-bottom: 20px;
    .el-tag + .el-tag, .button-new-tag {
      margin-left: 10px;
    }
    .selectInput {
      margin-left: 10px;
    }
  }
}
</style>
